#连接数据库
import pymysql
host='localhost'
port=3306
user='root'
password='root'
database='market'
charset='utf8'
def get_connect():
    db = pymysql.Connect(host=host, port=port, user=user, password=password, database=database, charset=charset)
    print('数据库已连接')
    return db

#读取数据
def read_data(sql):
    db=get_connect()
    cursor=db.cursor()
    data=None
    try:
        cursor.execute(sql)#执行sql语句
        data=cursor.fetchall()#显示出所有查询数据
        print('读取数据')
    except Exception as e:
        print(e)
    cursor.close()
    db.close()
    return  data
#写入数据
def write_data(sql):
    db=get_connect()
    cursor=db.cursor()
    rows=0
    try:
        rows=cursor.execute(sql)
        db.commit()
        print('写入数据')
    except Exception as e:
        print(e)
        db.rollback()
    cursor.close()
    db.close()
    return rows

# if __name__=='__main__':
#     # sql='delete from products where id=1'
#     # print(write_data(sql))




